package com.ace.log.core.scope

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import java.io.Closeable
import kotlin.coroutines.CoroutineContext


typealias coroutineErrorListener = (throwable: Throwable) -> Unit

val IO: CoroutineDispatcher = Dispatchers.IO

fun ioScope(errorHandler: coroutineErrorListener?=null) = SafeCoroutineScope(IO,errorHandler)

class SafeCoroutineScope(context: CoroutineContext, errorHandler: coroutineErrorListener?=null) : CoroutineScope,
    Closeable {

    override val coroutineContext: CoroutineContext = SupervisorJob() + context + UncaughtCoroutineExceptionHandler(errorHandler)

    override fun close() {
        coroutineContext.cancelChildren()
    }
}


